import { app, BrowserWindow, ipcMain, shell, dialog, Menu } from 'electron'
import path from 'path'
import { InstanceManager } from './instanceManager'

// --- 单例应用 ---
// 请求单一实例锁
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  // 如果获取锁失败，说明已经有一个实例在运行，则直接退出
  app.quit()
} else {
  // 当尝试启动第二个实例时，此事件将在主实例中触发
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    const existingWindows = BrowserWindow.getAllWindows();
    if (existingWindows.length > 0) {
      const mainWindow = existingWindows[0];
      if (mainWindow) {
        // 如果窗口被最小化，则恢复
        if (mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        // 将窗口置于前台
        mainWindow.focus();
        mainWindow.show();
        
        // 显示提醒消息
        dialog.showMessageBox(mainWindow, {
          type: 'info',
          title: '应用已运行',
          message: '氮化镓紫外局放监测系统已经在运行中',
          detail: '请使用当前已打开的窗口，无需重复启动。',
          buttons: ['确定']
        });
      }
    }
  });

  const windows = new Set<BrowserWindow>()
  const managers = new Map<number, InstanceManager>()
  let isQuitting = false
  let instanceCounter = 0 // 添加一个实例计数器，用于生成唯一ID

  // 监听渲染进程的死亡
  app.on('render-process-gone', (event, webContents, details) => {
    console.log('Render process gone:', details);
    // 查找导致渲染进程死亡的窗口
    const win = BrowserWindow.fromWebContents(webContents);
    if (win) {
      // 重启窗口
      win.reload()
    }
  })

  // 禁用硬件加速
  app.disableHardwareAcceleration()

  ipcMain.on('openDialog', (event, arg: string) => {
    shell.openPath(arg).catch(err => {
      console.error(`Failed to open path: ${arg}`, err)
    })
  })

  ipcMain.on('resize-window', (event) => {
    console.log('Received resize-window event from renderer process.'); // 添加日志
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      console.log(`Resizing window ${win.id} to 1200x800.`); // 添加日志
      win.setSize(1000, 800, true) // true for animated
      win.center()
    } else {
      console.error('Could not find window to resize.'); // 添加错误日志
    }
  })

  ipcMain.on('show-titlebar', (event) => {
    console.log('Received show-titlebar event from renderer process.');
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      console.log(`Window ${win.id} titlebar show request received (frame is always hidden).`);
      // 由于使用 frame: false，标题栏始终隐藏
      // 这里可以添加其他需要的逻辑
    } else {
      console.error('Could not find window to show titlebar.');
    }
  })

  ipcMain.on('hide-titlebar', (event) => {
    console.log('Received hide-titlebar event from renderer process.');
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      console.log(`Window ${win.id} titlebar hide request received (frame is always hidden).`);
      // 由于使用 frame: false，标题栏始终隐藏
      // 这里可以添加其他需要的逻辑
    } else {
      console.error('Could not find window to hide titlebar.');
    }
  })

  ipcMain.on('minimize-window', (event) => {
    console.log('Received minimize-window event from renderer process.');
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      console.log(`Minimizing window ${win.id}.`);
      win.minimize();
    } else {
      console.error('Could not find window to minimize.');
    }
  })

  ipcMain.on('toggle-maximize', (event) => {
    console.log('Received toggle-maximize event from renderer process.');
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      if (win.isMaximized()) {
        console.log(`Restoring window ${win.id}.`);
        win.restore();
      } else {
        console.log(`Maximizing window ${win.id}.`);
        win.maximize();
      }
      // 发送窗口状态变化事件
      win.webContents.send('window-state-changed', { isMaximized: win.isMaximized() });
    } else {
      console.error('Could not find window to toggle maximize.');
    }
  })

  ipcMain.on('close-window', (event) => {
    console.log('Received close-window event from renderer process.');
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      console.log(`Closing window ${win.id}.`);
      win.close();
    } else {
      console.error('Could not find window to close.');
    }
  })

  /**
   * 获取系统的标题
   */
  ipcMain.on('set-system-title',(event) => {
      console.log(event)
  })

  // 处理前端主动获取端口信息的请求
  ipcMain.handle('get-server-ports', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      const manager = managers.get(win.id)
      if (manager) {
        const ports = manager.getCurrentPorts()
        console.log(`窗口 ${win.id} 请求端口信息，返回:`, ports)
        return ports
      }
    }
    return null
  })

  // Menu.setApplicationMenu(null)
  // --- Window Creation ---
  const createBrowserWindow = async () => {
    const manager = new InstanceManager();
    
    // // 禁用多实例功能 - 已被新的单例模式取代
    // const instanceFile = (manager as any).readInstanceFile();
    // if (instanceFile.instances.length >= 3) { // MAX_INSTANCES = 3
    //   console.log('实例已达上限，退出应用。');
    //   dialog.showErrorBox('错误', '实例已达上限，请关闭其他实例。');
    //   app.quit(); // 完全退出应用
    //   return;
    // }

    instanceCounter++ // 为每个新实例递增计数器
    const partition = `persist:instance_${instanceCounter}` // 基于计数器创建唯一的 partition 名称

    const win = new BrowserWindow({
      width: 1000,
      height: 800,
      title: '氮化镓紫外局放监测系统',
      frame: false, // 完全隐藏标题栏
      webPreferences: {
        preload: path.resolve(__dirname, 'preload.js'),
        contextIsolation: true,
        nodeIntegration: false,
        partition: partition // 为 webPreferences 指定独立的 partition
      }
    });

    // 监听窗口状态变化
    win.on('maximize', () => {
      win.webContents.send('window-state-changed', { isMaximized: true });
    });
    
    win.on('unmaximize', () => {
      win.webContents.send('window-state-changed', { isMaximized: false });
    });

    // 窗口创建后再启动后端服务
    const canStart = await manager.startBackend(win.webContents);
    if (!canStart) {
      console.log('启动后端服务失败，关闭窗口。');
      win.close();
      return;
    }

    // 立即推送一次端口信息，以防后端启动过快，首次推送丢失
    const initialPorts = manager.getCurrentPorts();
    if (initialPorts) {
      win.webContents.send('server-ports-update', initialPorts);
    }

    managers.set(win.id, manager);
    windows.add(win);

    if (!app.isPackaged && process.env['VITE_DEV_SERVER_URL']) {
      win.loadURL(process.env['VITE_DEV_SERVER_URL']);
    } else {
      win.loadFile(path.join(__dirname, '../index.html'));
    }

    win.on('closed', () => {
      const managerToShutdown = managers.get(win.id);
      if (managerToShutdown) {
        managerToShutdown.shutdownBackend();
        managers.delete(win.id);
      }
      windows.delete(win);
    });
  }

  // --- Application Lifecycle ---
  app.on('ready', async () => {
    console.log('应用启动中 (ready event)...')
    await createBrowserWindow()
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createBrowserWindow()
    }
  });

  app.on('will-quit', async (event) => {
    if (isQuitting) return;
    event.preventDefault(); // 阻止应用立即退出
    isQuitting = true;

    console.log('应用即将退出 (will-quit event)，开始最终清理...');

    try {
      // 优雅地关闭所有实例
      const cleanupPromises = Array.from(managers.values()).map(manager => manager.shutdownBackend());
      await Promise.allSettled(cleanupPromises); // 使用 allSettled 确保所有清理都尝试执行
      console.log('所有实例的清理工作完成。');
      
      // 额外的强制清理：确保所有后端进程都被终止
      if (process.platform === 'win32') {
        try {
          // 查找并终止所有可能的后端进程
          const { exec } = require('child_process');
          if (app.isPackaged) {
            // 生产环境
            exec('taskkill /F /IM catl_server.exe /IM node.exe', (error) => {
              if (error && !error.message.includes('not found')) {
                console.log('强制终止后端进程结果:', error.message);
              } else {
                console.log('已强制终止所有后端进程');
              }
            });
          } else {
            // 开发环境：更精确地清理后端服务
            exec('netstat -ano | findstr :3000', (error, stdout) => {
              if (!error && stdout) {
                const lines = stdout.split('\n');
                lines.forEach(line => {
                  const match = line.match(/\s+(\d+)$/);
                  if (match) {
                    const pid = match[1];
                    exec(`taskkill /F /PID ${pid}`, (killError) => {
                      if (!killError) {
                        console.log(`已终止端口3000上的进程 PID: ${pid}`);
                      }
                    });
                  }
                });
              }
            });
            // 同时清理可能的node进程（但要避免杀死当前进程）
            exec(`taskkill /F /IM node.exe /FI "PID ne ${process.pid}"`, (error) => {
              if (error && !error.message.includes('not found')) {
                console.log('清理node进程结果:', error.message);
              } else {
                console.log('已清理其他node进程');
              }
            });
          }
        } catch (error) {
          console.error('强制清理后端进程失败:', error);
        }
      }
    } catch (error) {
      console.error('清理过程中发生错误:', error);
    } finally {
      // 延迟退出，确保清理完成
      setTimeout(() => {
        console.log('强制退出应用。');
        app.exit();
      }, 2000);
    }
  });

  // 处理各种退出信号
  process.on('SIGINT', () => { 
    console.log('收到 SIGINT 信号，准备退出...'); 
    isQuitting = true;
    app.quit(); 
  })

  process.on('SIGTERM', () => { 
    console.log('收到 SIGTERM 信号，准备退出...'); 
    isQuitting = true;
    app.quit(); 
  })

  // 处理开发环境中的强制退出
  process.on('exit', () => {
    console.log('主进程正在退出，执行最后的清理...');
    if (process.platform === 'win32') {
      try {
        // 开发环境和生产环境都执行强制清理
        if (app.isPackaged) {
          // 生产环境：清理打包后的可执行文件
          require('child_process').execSync('taskkill /F /IM catl_server.exe /IM node.exe', { stdio: 'ignore' });
        } else {
          // 开发环境：清理node进程和可能的后端服务
          require('child_process').execSync('taskkill /F /IM node.exe', { stdio: 'ignore' });
          // 尝试清理可能的后端服务进程
          require('child_process').execSync('netstat -ano | findstr :3000 | findstr LISTENING', { stdio: 'pipe' }).toString().split('\n').forEach(line => {
            const match = line.match(/\s+(\d+)$/);
            if (match) {
              try {
                require('child_process').execSync(`taskkill /F /PID ${match[1]}`, { stdio: 'ignore' });
              } catch (e) {
                // 忽略错误
              }
            }
          });
        }
        console.log('已在进程退出时强制清理后端进程');
      } catch (error) {
        // 忽略错误，可能是进程已经不存在
        console.log('进程清理完成（部分命令可能失败，这是正常的）');
      }
    }
  })

  // 处理未捕获的异常
  process.on('uncaughtException', (error) => {
    console.error('未捕获的异常:', error);
    isQuitting = true;
    // 强制清理并退出
    setTimeout(() => {
      process.exit(1);
    }, 1000);
  })
}